/*
 * @Author: 抱著羊啃 1437670973@qq.com
 * @Date: 2025-05-19 19:14:39
 * @LastEditors: 抱着羊啃 1437670973@qq.com
 * @LastEditTime: 2025-05-27 20:13:50
 * @FilePath: \demo1\src\main\java\org\example\demo1\servlets\functionPage\NovelServlet.java
 * @Description: 這DEFAULT_SETTING, 請設置`customMade`, 打開koroFileHeader查看配置 進行設置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
package org.example.demo1.servlets.functionPage;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.apache.ibatis.session.SqlSession;
import org.example.demo1.DAO.NovelDao;
import org.example.demo1.DAO.RolePermissionDao;
import org.example.demo1.DAO.UserRoleDao;
import org.example.demo1.Entity.Novel;
import org.example.demo1.Entity.User;
import org.example.demo1.utils.MybatisUtils;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

@WebServlet("/API/Novel/*")
public class NovelServlet extends HttpServlet{
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置响应内容类型
        resp.setContentType("application/json;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        
        // 获取分页参数
        int pageNum = 1;
        int pageSize = 9; // 每页10条数据
        
        try {
            // 获取请求中的分页参数
            String pageNumStr = req.getParameter("pageNum");
            if (pageNumStr != null && !pageNumStr.isEmpty()) {
                pageNum = Integer.parseInt(pageNumStr);
            }
            
            String pageSizeStr = req.getParameter("pageSize");
            if (pageSizeStr != null && !pageSizeStr.isEmpty()) {
                pageSize = Integer.parseInt(pageSizeStr);
            }
            
            // 获取查询条件（新增分类ID参数）
            String novelName = req.getParameter("novel_name");
            String authorIdStr = req.getParameter("author_id");
            String category = req.getParameter("category"); // 新增：获取分类ID参数
            
            // 获取查询条件（新增状态参数）
            String status = req.getParameter("status");  // 从请求中获取状态参数
            
            // 获取字数范围参数
            String wordCountRange = req.getParameter("wordCountRange");
            
            // 计算偏移量
            int offset = (pageNum - 1) * pageSize;
            
            // 查询数据库
            SqlSession sqlSession = MybatisUtils.getSqlSession();
            NovelDao novelDao = sqlSession.getMapper(NovelDao.class);
            
            // 构建查询条件（新增分类ID）
            Map<String, Object> params = new HashMap<>();
            params.put("offset", offset);
            params.put("pageSize", pageSize);
            
            if (novelName != null && !novelName.isEmpty()) {
                params.put("novel_name", "%" + novelName + "%");
            }
            
            if (authorIdStr != null && !authorIdStr.isEmpty()) {
                try {
                    int authorId = Integer.parseInt(authorIdStr);
                    params.put("author_id", authorId);
                } catch (NumberFormatException e) {
                    // 忽略无效的作者ID
                }
            }
            
            if (category != null && !category.isEmpty()) { // 新增：添加分类ID到参数
                params.put("category", Integer.parseInt(category));
            }
            
            // 构建查询条件（新增状态参数）
            if (status != null && !status.isEmpty()) { 
                params.put("status", Integer.parseInt(status));  // 传递到MyBatis参数
            }
            
            // 添加字数范围参数
            if (wordCountRange != null && !wordCountRange.isEmpty()) {
                switch (wordCountRange) {
                    case "lt30w":
                        params.put("minWordCount", 0);
                        params.put("maxWordCount", 300000);
                        break;
                    case "30w-50w":
                        params.put("minWordCount", 300000);
                        params.put("maxWordCount", 500000);
                        break;
                    case "50w-100w":
                        params.put("minWordCount", 500000);
                        params.put("maxWordCount", 1000000);
                        break;
                    case "100w-200w":
                        params.put("minWordCount", 1000000);
                        params.put("maxWordCount", 2000000);
                        break;
                    case "gt200w":
                        params.put("minWordCount", 2000000);
                        params.put("maxWordCount", Integer.MAX_VALUE);
                        break;
                }
            }
            
            // 添加排序参数，设置为ASC（升序）
            params.put("orderDirection", "ASC");
            
            // 查询小说列表
            List<Novel> novels = novelDao.getNovelListPagination(params);
            
            // 查询总记录数
            int total = novelDao.getNovelCount(params);
            
            // 构建响应数据
            Map<String, Object> result = new HashMap<>();
            result.put("code", 200);
            result.put("msg", "查询成功");
            result.put("total", total);
            result.put("rows", novels);
            
            // 创建配置了序列化null值的Gson实例
            Gson gson = new GsonBuilder()
                    .serializeNulls()  // 这行配置会让Gson序列化null值
                    .setDateFormat("yyyy-MM-dd HH:mm:ss")  // 设置日期格式
                    .create();
            
            // 返回JSON数据
            out.write(gson.toJson(result));
            
            // 关闭SqlSession
            sqlSession.close();
        } catch (Exception e) {
            // 处理异常
            Map<String, Object> result = new HashMap<>();
            result.put("code", 500);
            result.put("msg", "查询失败：" + e.getMessage());
            
            Gson gson = new Gson();
            out.write(gson.toJson(result));
            
            e.printStackTrace();
        } finally {
            out.close();
        }
    }
}
